package com.vhly.tuite.twclient.util;

//import javax.microedition.io.HttpConnection;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;

/**
 * Created by IntelliJ IDEA.
 * User: vhly[FR]
 * Date: 2010-3-3
 * Time: 15:26:11
 */
public final class StreamUtil {
    public static void close(Object stream) {
        if (stream != null) {
            try {
                if (stream instanceof OutputStream) {
                    ((OutputStream) stream).close();
                } else if (stream instanceof InputStream) {
                    ((InputStream) stream).close();
                }/* else if(stream instanceof HttpConnection){
                    ((HttpConnection)stream).close();    // J2ME
                }*/
                else if (stream instanceof HttpURLConnection) {
                    ((HttpURLConnection) stream).disconnect();
                }
            } catch (IOException ioe) {
            }
        }
    }

    public static byte[] readInput(InputStream in) {
        byte[] ret = null;
        if (in != null) {
            byte[] buf = new byte[1024];
            ByteArrayOutputStream bout = null;
            try {
                bout = new ByteArrayOutputStream();
                int len;
                while (true) {
                    len = in.read(buf);
                    if (len == -1) {
                        break;
                    }
                    bout.write(buf, 0, len);
                }
                ret = bout.toByteArray();
                buf = null;
            } catch (IOException ioe) {

            }
        }
        return ret;
    }
}
